{% extends "base.html" %}

{% block content %}
<h3>Iterations by Projects</h3>
{% for iteration in iterations %}
<div id ="title-container" class="clearboth" val="{{ iteration.key.id}}">
    <h2><a href="/?id_it={{iteration.key.id}}">{{ iteration.name }}</a></h2>
    <div>
        <span>
            Project&nbsp;<a href="/iterations?project_id={{ iteration.get_project.key.id }}"
                            title="List all iterations">{{ iteration.get_project.name }}</a></span>
        |
        <span>Status: <span id="id_status">{{ iteration.status }}</span></span>
        |
        <span>{{ iteration.start_date|date:"D, M j, Y" }}</span>
        <span>-</span>
        <span>{{ iteration.end_date|date:"D, M j, Y" }}</span>
        <span class="float_right">
            <span>
                <a href="/story_form?iteration_id={{ iteration.key.id }}">Add Story</a>
            </span>
            <span>
                <a href="/iteration_form?id={{ iteration.key.id}}" id="id_close_link">Edit</a>
            </span>
            {% if iteration.status == "Inactive" %}
            <span><a href="#" val="Active" id="id_start" class="status">Start</a>
            </span>
            <span><a href="#" val="Closed" id="id_close" class="hide status" >Close</a></span>
            <span><a href="#" val="Active" id="id_reactive" class="hide status" >Reactive</a></span>
            {% else %}
            {% if iteration.status == "Active" %}
            <span><a href="#" val="Closed" id="id_close" class="status">Close</a></span>
            <span><a href="#" val="Active" id="id_reactive" class="hide status" >Reactive</a></span>
            {% else %}
            <span><a href="#" val="Active" class="status">Reactive</a></span>
            <span><a href="#" val="Closed" class="hide status" >Close</a></span>
            {% endif %}
            {% endif %}
            <span><a href="/stories_backlog?id={{iteration.key.id}}">Review</a></span>
            <span><a href="/iteration_planning?id={{iteration.key.id}}">Planning</a></span>
        </span>
    </div>
    <div >
    </div>
</div>
<div id="story-contain" class="ui-widget">
    <table>
        <col width="50%" />
        <col width="50%" />
        <thead>
            <tr>
                {% with iteration.count_stories as total_stories %}
                <th>
                    <div class="col_label ui-widget-content ui-widget-header border_w ui-state-default _ui-corner-all">
                        <div class="column_title">
                            <span>Done</span>
                        </div>
                        <div class="column_detail">
                            <span>{{ iteration.count_closed_stories }}/{{ total_stories }}</span>
                        </div>
                    </div>
                </th>
                <th>
                    <div class="col_label ui-widget-content ui-widget-header border_w ui-state-default _ui-corner-all">
                        <div class="column_title">
                            <span>Progress</span>
                        </div>
                        <div class="column_detail">
                            <span>{{ iteration.count_active_stories }}/{{ total_stories }}</span>
                        </div>
                        <div class="float_right plus_task">
                            <span id="id_add_story_{{iteration.key.id}}" val="{{iteration.key.id}}" title="Add new task"class="ui-icon ui-icon-plusthick cursor_pointer"></span>
                        </div>
                    </div>
                </th>
                {% endwith %}
            </tr>
        </thead>
        <tbody>
            <tr>
                <td class="ui-widget-content_ _ui-corner-all" valign="top">
                    {% for story in iteration.get_closed_stories %}
                    <div class="body ui-widget-content ui-corner-all">
                        <div class="story">
                            {% with story.key.id as id_story %}
                            <div>
                                <a href="/story?id={{ id_story }}"> {{ story.name|escape }}</a>
                            </div>
                            <div class="column_detail" >
                                <span>{{ story.category }}</span> |
                                <span>{{ story.priority }}</span> |
                                <span>{{ story.assigned_to }}</span> |
                                <span>{{ story.estimated_time }}</span>
                            </div>
                            <div id="id_pb_{{ id_story }}" val="{{story.percentage}}"></div>
                            {% endwith %}
                        </div>
                    </div>
                    {% endfor %}
                </td>
                <td class="ui-widget-content_ _ui-corner-all" valign="top">
                    {% for story in iteration.get_active_stories %}
                    <div class="body ui-widget-content ui-corner-all">
                        <div class="story">
                            {% with story.key.id as id_story%}
                            <div class="ui-state-highlight_ ui-state-active_ _ui-widget-header ui-corner-top name">
                                <a href="/story?id={{ id_story }}"> {{ story.name|escape }}</a>
                            </div>
                            <div class="column_detail" >
                                <span>{{ story.category }}</span> |
                                <span>{{ story.priority }}</span> |
                                <span id="id_status_{{id_story}}" val="{{ id_story }}">{{ story.status }}</span> |
                                <span id="id_assigned_to_{{id_story}}">{{ story.assigned_to }}</span> |
                                <span id="label_time_{{id_story}}">{{ story.estimated_time }}</span>
                            </div>
                            <div id="id_pb_{{ id_story }}" val="{{story.percentage}}"></div>
                            <div>
                                <span id="id_assign_{{id_story}}" val="{{ id_story }}" dir="{{ iteration.key.id }}" title="Assign" class="ui-icon ui-icon-transferthick-e-w cursor_pointer float_left icon_action"></span>
                                <span id="id_resolve_{{id_story}}" val="{{ id_story }}" title="Resolve" class="ui-icon ui-icon-check cursor_pointer float_left icon_action"></span>
                                <span id="id_time_{{id_story}}" val="{{ id_story }}" title="Time" class="ui-icon ui-icon-clock cursor_pointer float_left icon_action"></span>
                                <span id="id_reactive_{{id_story}}" val="{{ id_story }}" title="Reactive" class="ui-icon ui-icon-folder-open cursor_pointer float_left icon_action"></span>
                                <span id="id_close_{{id_story}}" val="{{ id_story }}" title="Close" class="ui-icon ui-icon-power cursor_pointer float_left icon_action"></span>
                                <span id="id_comment_{{id_story}}" val="{{ id_story }}" title="Comment" class="ui-icon ui-icon-comment cursor_pointer icon_action"></span>
                            </div>
                            {% endwith %}
                        </div>
                    </div>
                    {% endfor %}
                </td>
            </tr>
        </tbody>
    </table>
</div>

<select id="id_users_{{iteration.key.id}}" class="hide">
    {% for member in iteration.get_project.get_members %}
    <option value="{{ member.key.id }}">{{ member.user.nickname }}</option>
    {% endfor%}
</select>

{% endfor %}

<div id="dialog_story_form" title="Create new story">
    <p class="validate_tips">Fill out all form fields.</p>
    <form action="/create_story" method="post">
        <input type="hidden" name="iteration_id" value="{{iteration.key.id}}">
        <fieldset>
            <ol>
                {{ story_form.as_ul }}
                <li>
                    <label for="id_assigned_to">Assigned to:</label>
                    <select name="assigned_to" id="id_assigned_to" class="select ui-widget-content ui-corner-all">
                    </select>
                </li>
            </ol>
        </fieldset>
    </form>
</div>

<div id="assign_form" class="form_container" title="Assign" >
    <p class="validate_tips">Fill out all form fields.</p>
    <form action="/assign_form" method="post" id="assignForm">
        <input type="hidden" name="story_id" value="">
        <fieldset>
            <ol>
                <li>
                    <label for="id_assigned_to">Assigned to:</label>
                    <select name="assigned_to" id="id_assigned_to" class="select ui-widget-content ui-corner-all">
                    </select>
                </li>
                <li>
                    <label for="id_description">Description:</label>
                    <textarea cols="50" rows="5" id="id_description" name="description" class="text ui-widget-content ui-corner-all description"></textarea>
                </li>
            </ol>
        </fieldset>
    </form>
</div>

<div id="resolve_form" title="Change status" class="form_container">
    <p class="validate_tips">Fill out all form fields.</p>
    <form action="/change_story_status" method="post" id="resolveForm">
        <input type="hidden" name="story_id" value="">
        <fieldset>
            <ol>
                <li>
                    <label for="id_status">Status:</label>
                    <select name="status" id="id_status" class="select ui-widget-content ui-corner-all">
                        <option value="Implemented">Implemented</option>
                        <option value="Fixed">Fixed</option>
                        <option value="No Reproducible">No Reproducible</option>
                        <option value="Duplicated">Duplicated</option>
                    </select>
                </li>
                <li>
                    <label for="id_description">Description:</label>
                    <textarea  cols="50" rows="5" id="id_description" name="description" class="text ui-widget-content ui-corner-all description"></textarea>
                </li>
            </ol>
        </fieldset>
    </form>
</div>

<div id="time_form" class="form_container" title="Reopen">
    <p class="validate_tips">Fill out all form fields.</p>
    <form action="/add_time_worked" method="post" id="timeForm">
        <input type="hidden" name="story_id" value="">
        <fieldset>
            <ol>
                <li>
                    <label for="name">Time</label>
                    <input type="text" name="time" id="id_elapsed_time" class="text ui-widget-content ui-corner-all">
                </li>
                <li>
                    <label for="id_description">Description:</label>
                    <textarea  cols="50" rows="5" id="id_description" name="description" class="text ui-widget-content ui-corner-all description"></textarea>
                </li>
            </ol>
        </fieldset>
    </form>
</div>

<div id="comment_form" class="form_container" title="Comment">
    <p class="validate_tips">Fill out all form fields.</p>
    <form action="/comment_story" method="post" id="commentForm">
        <input type="hidden" name="story_id" value="">
        <fieldset>
            <ol>
                <li>
                    <label for="id_comment">Comment:</label>
                    <textarea  cols="50" rows="5" id="id_comment" name="comment" class="text ui-widget-content ui-corner-all description"></textarea>
                </li>
            </ol>
        </fieldset>
    </form>
</div>

<div id="close_form" class="form_container" title="Close">
    <p class="validate_tips">Fill out all form fields.</p>
    <form action="/change_story_status" method="post" id="closeForm">
        <input type="hidden" name="story_id" value="">
        <fieldset>
            <ol>
                <li>
                    <label for="id_description">Description:</label>
                    <textarea  cols="50" rows="5" id="id_description" name="description" class="text ui-widget-content ui-corner-all description"></textarea>
                </li>
            </ol>
        </fieldset>
    </form>
</div>

<div id="reactive_form" class="form_container" title="Reactive">
    <p class="validate_tips">Fill out all form fields.</p>
    <form action="/change_story_status" method="post" id="reactiveForm">
        <input type="hidden" name="story_id" value="">
        <fieldset>
            <ol>
                <li>
                    <label for="id_description">Description:</label>
                    <textarea  cols="50" rows="5" id="id_description" name="description" class="text ui-widget-content ui-corner-all description"></textarea>
                </li>
            </ol>
        </fieldset>
    </form>
</div>

<div id="error-message" title="Error!">
    <span>
        <span class="ui-icon ui-icon-alert" style="float: left; margin: 1px 7px 50px 0;"></span>
        <span id="warning_msg"></span>
    </span>
</div>

<script type="text/javascript">
    $(document).ready(function(){
        $('div:[id^=id_pb_]').each(function() {
            var percentage = parseFloat($(this).attr('val'));
            $(this).progressbar({value:percentage});
        });

        var elapsed_time = $( "#id_elapsed_time" );
        $( 'form input[type=text]' ).keydown(function(event) {
            if (event.keyCode == 13) {
                event.preventDefault();
                return false;
            }
        });

        $( "#time_form" ).dialog({
            autoOpen: false,
            height: 260,
            width: 480,
            modal: true,
            buttons: {
                "Save": function() {
                    var valid = true;
                    allFields.removeClass( "ui-state-error" );
                    valid = valid && checkRegexp( elapsed_time, /^[+-]?\d+(\.\d+)?$/i, "Elapsed time must be a number." );
                    if (valid) {
                        var $form = $( '#timeForm' ),
                        url = $form.attr( 'action' ),
                        id_story = $form.find( 'input[name="story_id"]' ).val(),
                        data = $form.serialize() + '&html=False';
                        $.ajax({
                            type: 'POST',
                            url: url,
                            dataType: 'json',
                            data: data,
                            success: function(data) {
                                $("#id_pb_"+id_story).progressbar({value: data.percentage});
                            },
                            error: function (data) {
                                showErrorMsg(data.responseText);
                            }
                        });
                        $( this ).dialog( "close" );
                    }
                },
                Cancel: function() {
                    $( this ).dialog( "close" );
                }
            },
            close: function() {
                resetStoryForm();
            }
        });
        $( 'span:[id^=id_time_]' ).click(function(event) {
            event.preventDefault();
            var id_story = $( this ).attr('val');
            $( '#timeForm' ).find( 'input[name="story_id"]' ).val(id_story);
            $( "#time_form" ).dialog( "open" );
        });

        $( "#assign_form" ).dialog({
            autoOpen: false,
            height: 260,
            width: 480,
            modal: true,
            buttons: {
                "Save": function() {
                    var $form = $('#assignForm'),
                    url = $form.attr( 'action' ),
                    id_story = $form.find( 'input[name="story_id"]' ).val(),
                    data = $form.serialize() + '&html=False';
                    $.ajax({
                        type: 'POST',
                        url: url,
                        dataType: 'json',
                        data: data,
                        success: function(data) {
                            $('#id_assigned_to_' + id_story).text(data.assigned_to);
                        },
                        error: function (data) {
                            showErrorMsg(data.responseText);
                        }
                    });
                    $( this ).dialog( "close" );
                },
                Cancel: function() {
                    $( this ).dialog( "close" );
                }
            },
            close: function() {
                resetStoryForm();
            }
        });
        $( 'span:[id^=id_assign_]' ).click(function(event) {
            event.preventDefault();
            var id_story = $( this ).attr('val'),
            id_iteration = $( this ).attr('dir');
            var options = $( '#id_users_' + id_iteration ).children().clone();
            $( '#assignForm' ).find( 'input[name="story_id"]' ).val(id_story);
            $('#assignForm select[name="assigned_to"]').empty().append(options);
            $( "#assign_form" ).dialog( "open" );
        });

        $( "#resolve_form" ).dialog({
            autoOpen: false,
            height: 260,
            width: 480,
            modal: true,
            buttons: {
                "Save": function() {
                    var $form = $( '#resolveForm' ),
                    url = $form.attr( 'action' ),
                    id_story = $form.find( 'input[name="story_id"]' ).val(),
                    data = $form.serialize() +'&html=False';
                    $.ajax({
                        type: 'POST',
                        url: url,
                        dataType: 'json',
                        data: data,
                        success: function(data) {
                            var html = $(data.html).html();
                            $('#id_status_' + id_story).text(data.status);
                            updateControls(data.status);
                        },
                        error: function (data) {
                            showErrorMsg(data.responseText);
                        }
                    });
                    $( this ).dialog( "close" );

                },
                Cancel: function() {
                    $( this ).dialog( "close" );
                }
            },
            close: function() {
                resetStoryForm();
            }
        });
        $( "span:[id^=id_resolve_]" ).click(function(event) {
            event.preventDefault();
            var id_story = $( this ).attr('val');
            $( '#resolveForm' ).find( 'input[name="story_id"]' ).val(id_story);
            $( "#resolve_form" ).dialog( "open" );
        });


        $( "#error-message" ).dialog({
            autoOpen: false,
            modal: true,
            buttons: {
                Ok: function() {
                    $( this ).dialog( "close" );
                }
            }
        });
        function showErrorMsg(msg) {
            $( '#warning_msg' ).text(msg);
            $( "#error-message" ).dialog( "open" );
        }

        $('.status').click(function(event) {
            event.preventDefault();
            var iteration_id = $( this ).parent().parent().parent().parent().attr('val'),
            status = $(this).attr( 'val' );
            $.ajax({
                type: 'POST',
                url: '/change_iteration_status',
                dataType: 'json',
                data: { iteration_id: iteration_id, status: status },
                success: function(data) {
                    $('#id_status').text(data.status);
                    updateControls(data);
                }
            });
        });

        $( "#comment_form" ).dialog({
            autoOpen: false,
            height: 260,
            width: 480,
            modal: true,
            buttons: {
                "Save": function() {
                    var $form = $( '#commentForm' ),
                    url = $form.attr( 'action' ),
                    data = $form.serialize() + '&html=False';
                    $.ajax({
                        type: 'POST',
                        url: url,
                        dataType: 'json',
                        data: data,
                        success: function(data) {
                            var html = $(data.html).html();
                            $('#id_events').append(html);
                        },
                        error: function (data) {
                            showErrorMsg(data.responseText);
                        }
                    });
                    $( this ).dialog( "close" );
                },
                Cancel: function() {
                    $( this ).dialog( "close" );
                }
            },
            close: function() {
                resetStoryForm();
            }
        });
        $( "span:[id^=id_comment_]" ).click(function(event) {
            event.preventDefault();
            var id_story = $( this ).attr('val');
            $( '#commentForm' ).find( 'input[name="story_id"]' ).val(id_story);
            $( "#comment_form" ).dialog( "open" );
        });

        var name = $( "#id_name" ),
        estimated_time = $( "#id_estimated_time" ),
        description = $( "#id_description" ),
        tips = $( ".validate_tips" ),
        allFields = $( [] ).add( name ).add( estimated_time ).add( description );
        function updateTips( t ) {
            tips
            .text( t )
            .addClass( "ui-state-highlight" );
            setTimeout(function() {
                tips.removeClass( "ui-state-highlight", 1500 );
            }, 5500 );
        }
        function checkLength( o, n, min ) {
            if ( o.val().length < min ) {
                o.addClass( "ui-state-error" );
                updateTips(  n + " is required." );
                return false;
            } else {
                return true;
            }
        }
        function checkRegexp( o, regexp, n ) {
            if ( !( regexp.test( o.val() ) ) ) {
                o.addClass( "ui-state-error" );
                updateTips( n );
                return false;
            } else {
                return true;
            }
        }
        function resetStoryForm() {
            tips.text('Fill out all form fields.');
            allFields.val( "" ).removeClass( "ui-state-error" );

        }
        $( "#dialog_story_form" ).dialog({
            autoOpen: false,
            height: 410,
            width: 600,
            modal: true,
            buttons: {
                "Save": function() {
                    var valid = true;
                    allFields.removeClass( "ui-state-error" );
                    valid = valid && checkLength( name, "Name", 3 );
                    valid = valid && checkRegexp( estimated_time, /^[+-]?\d+(\.\d+)?$/i, "Estimated time must be a number." );
                    if (valid) {
                        var $form = $('#dialog_story_form form'),
                        url = $form.attr('action'),
                        data = $form.serialize();
                        $.ajax({
                            type: 'POST',
                            url: url,
                            dataType: 'json',
                            data: data,
                            success: function(data) {
                                resetStoryForm();
                                location.reload();
                            }
                        });
                        $( this ).dialog( "close" );
                    }
                },
                Cancel: function() {
                    $( this ).dialog( "close" );
                }
            },
            close: function() {
                resetStoryForm();
            }
        });
        $( "span:[id^=id_add_story_]" ).click(function() {
            var id_iteration = $( this ).attr('val');
            var options = $( '#id_users_' + id_iteration ).children().clone();
            $( '#dialog_story_form input[name="iteration_id"]' ).val(id_iteration);
            $('#dialog_story_form form select[name="assigned_to"]').empty().append(options);
            $( "#dialog_story_form" ).dialog( "open" );
        });

        $( "#close_form" ).dialog({
            autoOpen: false,
            height: 260,
            width: 480,
            modal: true,
            buttons: {
                "Save": function() {
                    var $form = $( '#closeForm' ),
                    url = $form.attr( 'action' ),
                    data = $form.serialize() + '&status=Closed&html=False';
                    $.ajax({
                        type: 'POST',
                        url: url,
                        dataType: 'json',
                        data: data,
                        success: function(data) {
                            var html = $(data.html).html();
                            $('#id_events').append(html);
                            updateControls(data.status);
                        },
                        error: function (data) {
                            showErrorMsg(data.responseText);
                        }
                    });
                    $( this ).dialog( "close" );
                },
                Cancel: function() {
                    $( this ).dialog( "close" );
                }
            },
            close: function() {
                resetStoryForm();
            }
        });
        $( 'span:[id^=id_close_]' ).click(function(event) {
            event.preventDefault();
            var id_story = $( this ).attr('val');
            $( '#closeForm' ).find( 'input[name="story_id"]' ).val(id_story);
            $( "#close_form" ).dialog( "open" );
        });

        $( "#reactive_form" ).dialog({
            autoOpen: false,
            height: 260,
            width: 480,
            modal: true,
            buttons: {
                "Save": function() {
                    var $form = $( '#reactiveForm' ),
                    url = $form.attr( 'action' ),
                    data = $form.serialize() + '&status=Active&html=False';
                    $.ajax({
                        type: 'POST',
                        url: url,
                        dataType: 'json',
                        data: data,
                        success: function(data) {
                            var html = $(data.html).html();
                            $('#id_events').append(html);
                            updateControls(data.status);
                            $('#reactive_form').addClass('hide');
                        },
                        error: function (data) {
                            showErrorMsg(data.responseText);
                        }
                    });
                    $( this ).dialog( "close" );
                },
                Cancel: function() {
                    $( this ).dialog( "close" );
                }
            },
            close: function() {
                resetStoryForm();
            }
        });
        $( 'span:[id^=id_reactive_]' ).click(function(event) {
            event.preventDefault();
            var id_story = $( this ).attr('val');
            $( '#reactiveForm' ).find( 'input[name="story_id"]' ).val(id_story);
            $( "#reactive_form" ).dialog( "open" );
        });

        function updateControls(data) {
            if (data.status == 'Active') {
                $('#id_close').removeClass('hide');
                $('#id_reactive, #id_start').addClass('hide');
            } else {
                if (data.status == 'Closed') {
                    $('#id_reactive').removeClass('hide');
                    $('#id_start, #id_close').addClass('hide');
                }
            }
        }

        $.each($( 'span[id^=id_status_]' ), function(index, value) {
            updateStoryControls($(value).text(), $( this ).attr('val'));
        });
        function updateStoryControls(status, id_story) {
            var user_valid = '{{story.contains_current_user}}';
            var resolve_status = ['Implemented', 'Fixed', 'No Reproducible', 'Duplicated'];
            $('#status_label').text(status);
            if (status == 'Active') {
                $('#id_resolve_'+id_story+', #id_assign_'+id_story+', #id_comment_+id_story+').removeClass('hide');
                $('#id_close_'+id_story+', #id_reactive_'+id_story).addClass('hide');
            } else {
                if (include(resolve_status, status)) {
                    $('#id_close_'+id_story+', #id_reactive_'+id_story+',  #id_assign_'+id_story+'').removeClass('hide');
                } else {
                    if (status == 'Closed') {
                        $('#id_close_'+id_story+', #id_reactive_'+id_story+', #id_resolve_'+id_story+'').addClass('hide');
                        $('#id_assign_'+id_story+', #id_comment_'+id_story+'').addClass('hide');
                    }
                }
            }
        }
        function include(array, value) {
            return ($.inArray(value, array) != -1);
        }
    });
</script>

{% endblock %}